package org.flown.novel.service;

import org.flown.novel.dao.UserDAO;
import org.flown.novel.data.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import java.sql.Timestamp;
import java.util.Date;


@Service
public class UserService
{
    private final UserDAO dao;
    private final QueryWrapper<User> qw = new QueryWrapper<>();

    public UserService(UserDAO dao)
    {
        this.dao = dao;
    }

    public User getUserByID(int user_id)
    {
        this.qw.clear();
        this.qw.eq(User.Column.ID.getName(), user_id);
        return this.dao.selectOne(this.qw);
    }

    public User getUserByUsername(String username)
    {
        this.qw.clear();
        this.qw.eq(User.Column.USERNAME.getName(), username);
        return this.dao.selectOne(this.qw);
    }


    public ServiceResult register(User user)
    {
        if (user.getUsername() == null)
            return ServiceResult.NULL_USERNAME;
        if (user.getPassword() == null)
            return ServiceResult.NULL_PASSWORD;
        this.qw.clear();
        this.qw.eq(User.Column.USERNAME.getName(), user.getUsername());
        if (this.dao.selectOne(this.qw) != null)
            return ServiceResult.EXISTS_NAME;

        if (this.dao.insert(user) == 0)
            return ServiceResult.FAILED;
        return ServiceResult.SUCCESS;
    }

    public ServiceResult login(String username, String password)
    {
        if (username == null)
            return ServiceResult.NULL_USERNAME;
        if (password == null)
            return ServiceResult.NULL_PASSWORD;
        this.qw.clear();
        this.qw.eq(User.Column.USERNAME.getName(), username);
        User user = this.dao.selectOne(this.qw);
        if (user == null)
            return ServiceResult.NOT_EXISTS_USER;

        if (user.getPassword().equals(password))
        {
            user.setLastLoginTime(new Date(System.currentTimeMillis()));
            this.dao.updateById(user);
            return ServiceResult.SUCCESS;
        }
        
        return ServiceResult.FAILED;
    }

    public ServiceResult changeNickname(User user)
    {
        this.qw.clear();
        this.qw.eq(User.Column.ID.getName(), user.getId());
        String original_nickname = this.dao.selectOne(this.qw).getNickname();
        if (original_nickname == null || original_nickname.equals(""))
            return ServiceResult.NOT_EXISTS_USER;
        
        //nickname不变则修改失败
        if(user.getNickname().equals(original_nickname))
            return ServiceResult.FAILED;

        this.dao.update(user, this.qw);
        return ServiceResult.SUCCESS;
    }
}
